import json
import time

from flask import Blueprint, make_response, session, request, jsonify

from app.config.ue_config import FEEDBACK_UECONFIG
from common import response_message
from common.utils import compress_image, model_to_json
from model.feedback import Feedback

feedback = Blueprint('feedback', __name__)


@feedback.before_request
def before_comment():
    if session.get('is_login') is None or session.get('is_login') != 'true':
        return {'status': 9999, 'data': '您好，请登录！'}


@feedback.route('/feedback', methods=['get', 'post'])
def ueditor():
    param = request.args.get('action')
    print(param)
    if request.method == 'GET' and param == 'config':
        return make_response(FEEDBACK_UECONFIG)
    elif param == 'image':
        f = request.files.get('file')
        filename = f.filename
        suffix = filename.split('.')[-1]
        newname = time.strftime('%Y%m%d_%H%M%S.' + suffix)
        f.save('resource/upload/' + newname)

        source = dest = "resource/upload" + newname
        compress_image(source, dest, 1200)

        result = {}
        result["state"] = "SUCCESS"
        result['url'] = "/upload/" + newname
        result["title"] = filename
        result["original"] = filename
        return jsonify(result)


@feedback.route('/feedback/add', methods=['POST'])
def add():
    request_data = json.loads(request.data)
    article_id = request_data.get('article_id')
    content = request_data.get('content').strip()
    ipaddr = request.remote_addr
    user_id = session.get('user_id')

    if len(content) < 5 or len(content) > 1000:
        return response_message.FeedbackMessage().other('内容长度不符')

    feedback = Feedback()
    try:
        result = feedback.insert_comment(
            user_id=user_id,
            article_id=article_id,
            content=content,
            ipaddr=ipaddr
        )
        result = model_to_json(result)
        return response_message.FeedbackMessage.success('评论成功')
    except Exception as e:
        print(e)
        return response_message.FeedbackMessage.error('评论失败')


@feedback.route('/feedback/reply', methods=['POST'])
def reply():
    request_data = json.loads(request.data)
    article_id = request_data.get('article_id')
    content = request_data.get('content').strip()
    ipaddr = request.remote_addr
    user_id = session.get('user_id')
    reply_id = request_data.get('reply_id')
    base_reply_id = request_data.get('base_reply_id')

    if len(content) < 5 or len(content) > 1000:
        return response_message.FeedbackMessage().other('内容长度不符')

    feedback = Feedback()
    try:
        result = feedback.insert_reply(
            article_id=article_id,
            user_id=user_id,
            content=content,
            ipaddr=ipaddr,
            reply_id=reply_id,
            base_reply_id=base_reply_id
        )
        return response_message.FeedbackMessage.success('评论成功')
    except Exception as e:
        print(e)
        return response_message.FeedbackMessage.error('评论失败')
